//
//  RegisterVC.m
//  PrivateSteward
//
//  Created by lanou3g on 16/3/26.
//  Copyright © 2016年 闫贺晨. All rights reserved.
//

#import "RegisterVC.h"
#import "UnloginPersonalHomePageVC.h"
#import "ResgisterSecurityPwdVC.h"
@interface RegisterVC ()<UITextFieldDelegate>
@property(nonatomic,strong)UITextField *smstextfiled;
@end

@implementation RegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    
    self.navigationController.navigationBar.hidden = NO;
    //self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"注册账号";
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];

}
-(void)viewWillAppear:(BOOL)animated
{
    self.regidterButton.enabled = YES;
}

-(void)initView
{
    self.myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.myView.backgroundColor = [UIColor colorWithRed:124/255.0 green:213/255.0 blue:254/255.0 alpha:1];
    [self.view addSubview:self.myView];
    
    //userIDLable
    self.userIDLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 80, 80, 40)];
    self.userIDLabel.backgroundColor = self.myView.backgroundColor;
    self.userIDLabel.textAlignment = NSTextAlignmentCenter ;
    self.userIDLabel.text = @"  用户名:";
    self.userIDLabel.textColor = [UIColor blackColor];
    [self.myView addSubview:self.userIDLabel];
    //userIDText
    self.userIDTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.userIDLabel.frame) + 10, CGRectGetMinY(self.userIDLabel.frame), self.myView.frame.size.width - self.userIDLabel.frame.size.width - 40, CGRectGetHeight(self.userIDLabel.frame))];
    self.userIDTextfiled.backgroundColor = [UIColor whiteColor];
    self.userIDTextfiled.layer.cornerRadius = 8;
    self.userIDTextfiled.textColor = [UIColor grayColor];
    self.userIDTextfiled.placeholder = @"请输入手机号";
    self.userIDTextfiled.clearsOnBeginEditing = YES;
    self.userIDTextfiled.delegate = self;
    [self.userIDTextfiled addTarget:self action:@selector(usertextfiled:) forControlEvents:UIControlEventEditingChanged];
    [self.myView addSubview:self.userIDTextfiled];
    //passwordlable
    self.passwordLable = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.userIDLabel.frame), CGRectGetMaxY(self.userIDLabel.frame) + 20, self.userIDLabel.frame.size.width, self.userIDLabel.frame.size.height)];
    self.passwordLable.backgroundColor = self.userIDLabel.backgroundColor;
    self.passwordLable.textColor = [UIColor blackColor];
    self.passwordLable.textAlignment = NSTextAlignmentCenter;
    self.passwordLable.text = @"    密码:";
    [self.myView addSubview:self.passwordLable];
    //passwordtextfiled
    self.passwordTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.userIDTextfiled.frame), CGRectGetMinY(self.passwordLable.frame), CGRectGetWidth(self.userIDTextfiled.frame), CGRectGetHeight(self.userIDTextfiled.frame))];
    self.passwordTextfiled.backgroundColor = [UIColor whiteColor];
    self.passwordTextfiled.layer.cornerRadius = 8;
    self.passwordTextfiled.textColor = [UIColor grayColor];
    self.passwordTextfiled.placeholder = @"请输入密码";
    self.passwordTextfiled.clearsOnBeginEditing = YES;
    self.passwordTextfiled.delegate = self;
    self.passwordTextfiled.secureTextEntry = YES;
    [self.passwordTextfiled addTarget:self action:@selector(usertextfiled:) forControlEvents:UIControlEventEditingChanged];
    [self.myView addSubview:self.passwordTextfiled];
    //surepasswordlable
    self.surePasswordLable = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.passwordLable.frame), CGRectGetMaxY(self.passwordLable.frame) + 20, self.passwordLable.frame.size.width, self.passwordLable.frame.size.height)];
    self.surePasswordLable.backgroundColor = self.myView.backgroundColor;
    self.surePasswordLable.textColor = [UIColor blackColor];
    self.surePasswordLable.text = @"确认密码:";
    self.surePasswordLable.textAlignment = NSTextAlignmentCenter;
    [self.myView addSubview:self.surePasswordLable];
    //surepasswordTextfiled
    self.surePasswordTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.passwordTextfiled.frame), CGRectGetMinY(self.surePasswordLable.frame), self.passwordTextfiled.frame.size.width, self.passwordTextfiled.frame.size.height)];
    self.surePasswordTextfiled.delegate = self;
    self.surePasswordTextfiled.placeholder = @"请再次输入密码";
    self.surePasswordTextfiled.textColor = [UIColor grayColor];
    self.surePasswordTextfiled.clearsOnBeginEditing = YES;
    self.surePasswordTextfiled.layer.cornerRadius = 8;
    self.surePasswordTextfiled.secureTextEntry = YES;
    self.surePasswordTextfiled.backgroundColor = [UIColor whiteColor];
    [self.surePasswordTextfiled addTarget:self action:@selector(usertextfiled:) forControlEvents:UIControlEventEditingChanged];
    [self.myView addSubview:self.surePasswordTextfiled];
    
    //registerbutton
    self.regidterButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.regidterButton.frame = CGRectMake(self.view.frame.size.width/2 - 50, CGRectGetMaxY(self.surePasswordTextfiled.frame) + 60, 100, 40);
    self.regidterButton.tintColor = [UIColor blackColor];
    self.regidterButton.backgroundColor = [UIColor colorWithRed:158/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    self.regidterButton.layer.cornerRadius = 8;
    self.regidterButton.titleLabel.font = [UIFont systemFontOfSize:18];
    self.regidterButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.myView addSubview:self.regidterButton];
    [self.regidterButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.regidterButton addTarget:self action:@selector(regsterAction:) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)regsterAction:(UIButton *)sender
{
    if ([self.passwordTextfiled.text isEqualToString:self.surePasswordTextfiled.text]) {
        //判断手机号格式是否正确
        if ([self validateMobile:self.userIDTextfiled.text]) {
            //发送短信
            AVUser *user = [AVUser user];// 新建 AVUser 对象实例
            user.username = self.userIDTextfiled.text;// 设置用户名
            user.password =  self.passwordTextfiled.text;// 设置密码
            user.mobilePhoneNumber = self.userIDTextfiled.text;
            [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    UIAlertController *alerV = [UIAlertController alertControllerWithTitle:@"请输入验证码" message:nil preferredStyle:UIAlertControllerStyleAlert];
                    //输入验证码点击确定,判断是否和手机上收到的验证码一致
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        //对验证码进行判断
                        [AVUser verifyMobilePhone:self.smstextfiled.text  withBlock:^(BOOL succeeded, NSError *error) {
                            if(succeeded){
                                AVObject *obj = [[AVObject alloc]initWithClassName:@"UserClass"];
                                [obj setObject:self.userIDTextfiled.text forKey:@"username"];
                                
                                NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"aboutus"], 0.1);
                                AVFile *file = [AVFile fileWithData:imageData];
                                [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                                    if (succeeded) {
                                        [obj setObject:file.url forKey:@"userImageUrl"];
                                        [obj setObject:self.userIDTextfiled.text forKey:@"phoneNumber"];
                                        [obj setObject:self.userIDTextfiled.text forKey:@"username"];
                                        [obj saveInBackground];
                                        self.regidterButton.enabled = NO;
                                        [self alertAction:@"注册成功" messageString:@"请到安全页面设置安全密码"];
                                    }
                                    else
                                    {
                                        [self alertAction:@"注册失败" messageString:@"重新注册"];
                                    }
                                }];
                            }
                            else
                            {
                                //存储的用户信息删除
                              [self alertAction:@"注册失败" messageString:@"验证码输入错误"];
                            }
                        }];
                    }];
                    [alerV addAction:action];
                    [alerV addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                        textField.text = @"";
                        self.smstextfiled = textField;
                    }];
                    [self presentViewController:alerV animated:YES completion:nil];

                }
                else {
                    
                    [self alertAction:@"注册失败" messageString:@"手机号已被注册"];
                    
                }
                
            }];
        }
        else
        {
            [self alertAction:@"注册失败" messageString:@"请输入正确的手机号"];
        }
    }else
    {
        [self alertAction:@"密码不一致" messageString:@"请重新输入"];
    }
    
}



-(void)alertAction:(NSString *)alertstring messageString:(NSString *)messageString
{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:alertstring message:messageString preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
             if ([alertstring isEqualToString:@"注册成功"]) {
//                UnloginPersonalHomePageVC *unloginVC = [[UnloginPersonalHomePageVC alloc]init];
//                [self.navigationController pushViewController:unloginVC animated:YES];
                 ResgisterSecurityPwdVC *rsVC = [[ResgisterSecurityPwdVC alloc]init];
                 [self.navigationController pushViewController:rsVC animated:YES];
            }
            }];
    [alert addAction:action];
    if([alertstring isEqualToString:@"密码不一致"])
    {
        self.passwordTextfiled.text = @"";
        self.surePasswordTextfiled.text = @"";
    }
    [self presentViewController:alert animated:YES completion:^{
    }];

}

-(void)usertextfiled:(UITextField *)sender
{
    if ([self.userIDTextfiled.text isEqualToString:@""]) {
        self.passwordTextfiled.enabled = NO;
        self.surePasswordTextfiled.enabled = NO;
    }
    else
    {
        self.passwordTextfiled.enabled = YES;
        self.surePasswordTextfiled.enabled = YES;
    }
    sender.textColor = [UIColor blackColor];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.userIDTextfiled resignFirstResponder];
    [self.passwordTextfiled resignFirstResponder];
    [self.surePasswordTextfiled resignFirstResponder];
    return YES;
}
-(BOOL)validateMobile:(NSString *)mobile
{
        //手机号以13， 15，18开头，八个 \d 数字字符
        NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
        NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
        return [phoneTest evaluateWithObject:mobile];
}


-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
